package com.simon.jkxj.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.simon.jkxj.R;
import com.simon.jkxj.model.Post;
import java.util.List;

public class PostAdapter extends RecyclerView.Adapter<PostAdapter.PostViewHolder> {
    private List<Post> postList;
    private OnItemClickListener onItemClickListener;

    public interface OnItemClickListener {
        void onItemClick(Post post, int position);
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.onItemClickListener = listener;
    }

    public PostAdapter(List<Post> postList) {
        this.postList = postList;
    }

    @NonNull
    @Override
    public PostViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_post, parent, false);
        return new PostViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull PostViewHolder holder, int position) {
        Post post = postList.get(position);
        holder.tvPostTitle.setText(post.getTitle());
        holder.tvPostPreview.setText(post.getContent());
        holder.tvUsername.setText(post.getUsername());
        holder.tvLikeCount.setText(String.valueOf(post.getLikeCount()));
        
        // 设置帖子图片
        holder.ivPostImage.setImageResource(post.getImageResourceId());
        // 新增：点击事件
        holder.itemView.setOnClickListener(v -> {
            if (onItemClickListener != null) {
                onItemClickListener.onItemClick(post, position);
            }
        });
    }

    @Override
    public int getItemCount() {
        return postList.size();
    }

    static class PostViewHolder extends RecyclerView.ViewHolder {
        ImageView ivPostImage;
        TextView tvPostTitle;
        TextView tvPostPreview;
        TextView tvUsername;
        TextView tvLikeCount;

        public PostViewHolder(@NonNull View itemView) {
            super(itemView);
            ivPostImage = itemView.findViewById(R.id.iv_post_image);
            tvPostTitle = itemView.findViewById(R.id.tv_post_title);
            tvPostPreview = itemView.findViewById(R.id.tv_post_preview);
            tvUsername = itemView.findViewById(R.id.tv_username);
            tvLikeCount = itemView.findViewById(R.id.tv_like_count);
        }
    }
} 